﻿using AutoMapper;
using Dm;
using MediatR;
using ProcurementManagement.Applcation.Command.PurchaseContractsCommand;
using ProcurementManagement.Domain.ProcurementDomain;
using ProcurementManagement.Infrstructre;
using ProcurementManagement.Infrstructre.Interface;
using SqlSugar;

namespace ProcurementManagement.Applcation.CommandHanlers.PurchaseContractsCommandHandler
{
    /// <summary>
    /// 添加采购合同命令处理器
    /// </summary>
    public class PurchaseContractsCreateCommandHandler : IRequestHandler<PurchaseContractsCreateCommand, int>
    {
        private readonly IPurchaseContractsRepository _purchaseContractsRep;
        private readonly ISourcProductContractRepository _sourceProductContractRep;
        private readonly ISqlSugarClient db;
        private readonly IMapper _mapper;
        public PurchaseContractsCreateCommandHandler(IPurchaseContractsRepository purchaseContractsRep, ISourcProductContractRepository sourceProductContractRep, ISqlSugarClient db, IMapper mapper)
        {
            this._purchaseContractsRep = purchaseContractsRep;
            this._sourceProductContractRep = sourceProductContractRep;
            this.db = db;
            this._mapper = mapper;
        }

        public async Task<int> Handle(PurchaseContractsCreateCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                // 将请求数据映射到实体
                var purchaseContract = _mapper.Map<PurchaseContracts>(request.AddPurchaseContractsDTO);

                // 插入采购合同
                int contractId = await _purchaseContractsRep.AddAsync(purchaseContract);

                // 假设需要插入相关的产品合同
                foreach (var item in request.AddPurchaseContractsDTO.Adddtos)
                {
                    SourcProductContract detail = new SourcProductContract
                    {
                        ProductId = item.ProductId,
                        SPCNum = item.SPCNum,
                        SPCPrice = item.SPCPrice,
                        SPCDocumentsType = item.SPCDocumentsType,
                        SPCTotalPrice = item.SPCTotalPrice,
                        SPCAfterPrice = item.SPCAfterPrice,
                        SPCAfterTotalPrice = item.SPCAfterTotalPrice,
                        SPCArrivalDate = item.SPCArrivalDate,
                        PCNumber = purchaseContract.PCNumber,
                        SPCRemark = item.SPCRemark,
                        SPPNumber= item.SPPNumber,
                        SPPName= item.SPPName,
                        SPPSpec = item.SPPSpec,
                        AddName = purchaseContract.AddName,
                        AddTime= purchaseContract.AddTime,
                        Office_Id= purchaseContract.Office_Id,
                        User_Id= purchaseContract.User_Id
                    };
                    
                    await _sourceProductContractRep.AddAsync(detail);
                }

                // 提交事务
                db.Ado.CommitTran();

                return 1; // 返回插入的合同 ID
            }
            catch (Exception ex)
            {
                // 捕获异常并回滚事务
                db.Ado.RollbackTran();
                // 可以记录日志以便调试
                throw new Exception("事务失败，已回滚所有操作", ex);
            }
        }
    }
}
